'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { 
  Dialog, 
  DialogContent, 
  DialogDescription, 
  DialogFooter, 
  DialogHeader, 
  DialogTitle 
} from '@/components/ui/dialog'
import { 
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible'
import { useToast } from '@/hooks/use-toast'
import { 
  ChevronRight, 
  ChevronDown, 
  Plus, 
  Settings, 
  AlertCircle,
  Loader2,
  Database 
} from 'lucide-react'
import { ParameterEntryDialog } from './parameter-entry-dialog'
import { PermissionGuard, usePermissions } from './permission-guard'
import { PBSLevelSelector } from './pbs-level-selector'

interface Device {
  device_id: string;
  name: string;
  classification_name: string;
  classification_code: string;
  specialty: string;
  sub_specialty?: string;
  naming_table?: string;
  position_table?: string;
  base_params_table?: string;
  naming_table_display?: string;
  position_table_display?: string;
  base_params_table_display?: string;
}

interface DeviceHierarchy {
  classification_name: string;
  specialty: string;
  devices: Device[];
}

interface DeviceInstance {
  id: number;
  device_type_code: string;
  instance_number: string;
  object_number: string;
  object_description: string;
  pbs_level_id?: number;  // PBS层级ID
  pbs_instance_id?: string;  // PBS实例ID
  created_at: string;
  updated_at: string;
  isEditing?: boolean; // 是否正在编辑状态
  isNew?: boolean; // 是否为新创建的行
  tempInstanceId?: number; // 临时实例ID
  // 表信息用于编辑时显示
  naming_table_display?: string;
  position_table_display?: string;
  base_params_table_display?: string;
  // 支持嵌入的参数字段
  [key: string]: any;
}

interface DeviceTypeTreeProps {
  specialty: string;
  subSpecialty?: string;
}

export function DeviceTypeTree({ specialty, subSpecialty }: DeviceTypeTreeProps) {
  const { toast } = useToast();
  const { canCreate, canDelete, isAuthenticated } = usePermissions();
  const [deviceHierarchies, setDeviceHierarchies] = useState<DeviceHierarchy[]>([]);
  const [deviceInstances, setDeviceInstances] = useState<Record<string, DeviceInstance[]>>({});
  const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set());
  const [expandedDevices, setExpandedDevices] = useState<Set<string>>(new Set());
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [parameterDialogOpen, setParameterDialogOpen] = useState(false);
  const [currentParameterTable, setCurrentParameterTable] = useState<{
    instanceId: number;
    deviceName: string;
    tableName: string;
    tableType: string;
    classificationCode: string;
  } | null>(null);
  const [savingInstances, setSavingInstances] = useState<Set<string>>(new Set());

  // 加载设备层次结构
  const loadDeviceHierarchies = async () => {
    try {
      setLoading(true);
      
      // 获取设备层次结构
      const response = await fetch(`/api/device-hierarchy-by-name?specialty=${encodeURIComponent(specialty)}`);
      const data = await response.json();
      
      if (!data.success) {
        throw new Error(data.error);
      }
      
      console.log('=== 设备层次结构数据 ===');
      console.log('原始数据:', data.data);
      console.log('第一个设备的表映射信息:', data.data[0]?.devices[0]);
      console.log('所有设备的表映射信息:');
      data.data.forEach((hierarchy: any, i: number) => {
        hierarchy.devices.forEach((device: any, j: number) => {
          console.log(`设备 ${i}-${j} (${device.name}):`, {
            naming_table: device.naming_table,
            position_table: device.position_table,
            base_params_table: device.base_params_table,
            naming_table_display: device.naming_table_display,
            position_table_display: device.position_table_display,
            base_params_table_display: device.base_params_table_display
          });
        });
      });
      // 根据子专业过滤数据
      let filteredData = data.data;
      if (subSpecialty) {
        filteredData = data.data.map((hierarchy: DeviceHierarchy) => ({
          ...hierarchy,
          devices: hierarchy.devices.filter((device: Device) => device.sub_specialty === subSpecialty)
        })).filter((hierarchy: DeviceHierarchy) => hierarchy.devices.length > 0);
      }
      
      setDeviceHierarchies(filteredData);
      
      // 加载所有设备的实例数量
      await loadAllDeviceInstanceCounts(filteredData);
      
    } catch (error) {
      console.error('加载设备层次结构失败:', error);
      setError(error instanceof Error ? error.message : '加载设备层次结构失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载所有设备的实例数量（仅统计数量，不加载详细数据）
  const loadAllDeviceInstanceCounts = async (hierarchies: DeviceHierarchy[]) => {
    try {
      const instanceCounts: Record<string, DeviceInstance[]> = {};
      
      // 收集所有设备ID
      const allDeviceIds = hierarchies.flatMap(h => h.devices.map(d => d.device_id));
      
      // 并行加载所有设备的实例数据
      const loadPromises = allDeviceIds.map(async (deviceId) => {
        try {
          const response = await fetch(`/api/device-instances?deviceTypeCode=${encodeURIComponent(deviceId)}`);
          const data = await response.json();
          
          if (data.success) {
            instanceCounts[deviceId] = data.data || [];
          } else {
            instanceCounts[deviceId] = [];
          }
        } catch (error) {
          console.error(`加载设备 ${deviceId} 实例失败:`, error);
          instanceCounts[deviceId] = [];
        }
      });
      
      await Promise.all(loadPromises);
      
      // 更新设备实例状态
      setDeviceInstances(instanceCounts);
      
      console.log('已加载所有设备实例数量:', Object.keys(instanceCounts).map(deviceId => `${deviceId}: ${instanceCounts[deviceId].length}`));
      
    } catch (error) {
      console.error('加载设备实例数量失败:', error);
    }
  };

  // 从表名提取显示代码，如 "table_c2" -> "C.2"
  const extractTableCode = (tableName: string): string => {
    if (!tableName) return '';
    const match = tableName.match(/table_c(\d+)/i);
    return match ? `C.${match[1]}` : tableName;
  };

  // 获取临时参数数据并转换为API可用格式
  const getTempParameterData = (instanceId: number, deviceTypeCode?: string) => {
    try {
      console.log('🔍 [FRONTEND] === getTempParameterData 调用 ===');
      console.log('🔍 [FRONTEND] instanceId:', instanceId);
      console.log('🔍 [FRONTEND] deviceTypeCode:', deviceTypeCode);
      
      // Try the format with deviceTypeCode first (newer format)
      let storedData = null;
      let usedKey = null;
      
      if (deviceTypeCode) {
        const keyWithCode = `tempParams_${instanceId}_${deviceTypeCode}`;
        storedData = localStorage.getItem(keyWithCode);
        if (storedData) {
          usedKey = keyWithCode;
          console.log('🔍 [FRONTEND] 使用带设备代码的键:', keyWithCode);
        }
      }
      
      // Fallback to older format without deviceTypeCode
      if (!storedData) {
        const keyWithoutCode = `tempParams_${instanceId}`;
        storedData = localStorage.getItem(keyWithoutCode);
        if (storedData) {
          usedKey = keyWithoutCode;
          console.log('🔍 [FRONTEND] 使用不带设备代码的键:', keyWithoutCode);
        }
      }
      
      if (!storedData) {
        console.log('❌ [FRONTEND] 未找到临时参数数据，尝试的键:');
        if (deviceTypeCode) {
          console.log('  -', `tempParams_${instanceId}_${deviceTypeCode}`);
        }
        console.log('  -', `tempParams_${instanceId}`);
        return null;
      }

      console.log('✅ [FRONTEND] 找到临时数据，使用键:', usedKey);
      const parsedData = JSON.parse(storedData);
      const result = {
        naming: {},
        position: {},
        base_params: {}
      };

      console.log('🔍 [FRONTEND] 解析临时数据:', JSON.stringify(parsedData, null, 2));

      // 解析参数数据，直接将字段ID映射的数据转换为字段名映射
      Object.entries(parsedData).forEach(([key, fieldData]) => {
        console.log('处理临时数据key:', key, fieldData);
        
        const [tempId, tableName] = key.split('-');
        if (tableName && fieldData && tempId == instanceId) {
          // 确定表类型
          let tableType = '';
          if (tableName.includes('table_c2') || tableName.includes('naming')) {
            tableType = 'naming';
          } else if (tableName.includes('table_c6') || tableName.includes('position')) {
            tableType = 'position';
          } else if (tableName.includes('table_c') || tableName.includes('base_params')) {
            tableType = 'base_params';
          }

          if (tableType) {
            // 直接使用字段ID作为临时字段名（后端会处理）
            const convertedData: Record<string, string> = {};
            Object.entries(fieldData as Record<number, string>).forEach(([fieldId, value]) => {
              if (value && String(value).trim()) {
                // 使用字段ID作为key，后端会根据字段定义来匹配
                convertedData[fieldId] = String(value).trim();
              }
            });
            
            if (Object.keys(convertedData).length > 0) {
              (result as any)[tableType] = convertedData;
              console.log(`设置${tableType}数据:`, convertedData);
            }
          }
        }
      });

      console.log('最终参数数据:', result);
      return Object.keys(result.naming).length === 0 && Object.keys(result.position).length === 0 && Object.keys(result.base_params).length === 0 ? null : result;
    } catch (error) {
      console.error('获取临时参数数据失败:', error);
      return null;
    }
  };

  // 将临时数据转移到新的实例ID
  const transferTempDataToNewInstance = (tempInstanceId: number, newInstanceId: number, deviceTypeCode?: string) => {
    // 从全局临时数据存储中获取数据
    const tempData = new Map<string, Record<number, string>>();
    
    // 模拟访问全局存储（由于React组件无法直接访问hook中的全局变量，我们通过localStorage作为桥梁）
    try {
      // Try both key formats
      let storedData = null;
      if (deviceTypeCode) {
        storedData = localStorage.getItem(`tempParams_${tempInstanceId}_${deviceTypeCode}`);
      }
      if (!storedData) {
        storedData = localStorage.getItem(`tempParams_${tempInstanceId}`);
      }
      
      if (storedData) {
        const parsedData = JSON.parse(storedData);
        Object.entries(parsedData).forEach(([key, value]) => {
          tempData.set(key, value as Record<number, string>);
        });
        
        // 将数据重新存储到新的实例ID下
        const newStorageData: Record<string, Record<number, string>> = {};
        tempData.forEach((data, tableName) => {
          const newKey = `${newInstanceId}-${tableName}`;
          newStorageData[newKey] = data;
        });
        
        const newStorageKey = deviceTypeCode ? `tempParams_${newInstanceId}_${deviceTypeCode}` : `tempParams_${newInstanceId}`;
        localStorage.setItem(newStorageKey, JSON.stringify(newStorageData));
        
        // Clean up old keys
        if (deviceTypeCode) {
          localStorage.removeItem(`tempParams_${tempInstanceId}_${deviceTypeCode}`);
        }
        localStorage.removeItem(`tempParams_${tempInstanceId}`);
        
        console.log('临时数据转移完成:', {
          from: tempInstanceId,
          to: newInstanceId,
          dataKeys: Object.keys(newStorageData)
        });
      }
    } catch (error) {
      console.error('转移临时数据失败:', error);
    }
  };

  // 加载指定设备的设备实例
  const loadDeviceInstances = async (deviceId: string) => {
    try {
      const response = await fetch(`/api/device-instances?deviceTypeCode=${encodeURIComponent(deviceId)}`);
      const data = await response.json();
      
      if (data.success) {
        // 为设备实例添加表映射信息
        const currentDevice = deviceHierarchies
          .flatMap(h => h.devices)
          .find(d => d.device_id === deviceId);

        console.log('加载设备实例时的调试信息:', {
          deviceId,
          currentDevice,
          naming_table_display: currentDevice?.naming_table_display,
          position_table_display: currentDevice?.position_table_display,
          base_params_table_display: currentDevice?.base_params_table_display
        });

        const enhancedInstances = data.data.map((instance: any) => ({
          ...instance,
          naming_table_display: currentDevice?.naming_table_display,
          position_table_display: currentDevice?.position_table_display,
          base_params_table_display: currentDevice?.base_params_table_display
        }));
        
        setDeviceInstances(prev => ({
          ...prev,
          [deviceId]: enhancedInstances
        }));
      } else {
        throw new Error(data.error);
      }
    } catch (error) {
      console.error('加载设备实例失败:', error);
      toast({
        title: '错误',
        description: '加载设备实例失败',
        variant: 'destructive'
      });
    }
  };

  // 切换设备分类展开/收起状态
  const toggleCategoryExpanded = (classificationName: string) => {
    const newExpanded = new Set(expandedCategories);
    
    if (newExpanded.has(classificationName)) {
      newExpanded.delete(classificationName);
    } else {
      newExpanded.add(classificationName);
    }
    
    setExpandedCategories(newExpanded);
  };

  // 切换设备展开/收起状态（显示实例列表）
  const toggleDeviceExpanded = async (deviceId: string) => {
    const newExpanded = new Set(expandedDevices);
    
    if (newExpanded.has(deviceId)) {
      newExpanded.delete(deviceId);
    } else {
      newExpanded.add(deviceId);
      // 展开时加载设备实例（仅在没有加载过时才加载）
      // 注意：现在实例数据在组件初始化时就已经加载了，这里主要是为了确保数据完整性
      if (!deviceInstances[deviceId] || deviceInstances[deviceId].length === 0) {
        await loadDeviceInstances(deviceId);
      }
    }
    
    setExpandedDevices(newExpanded);
  };

  // 根据设备添加新设备实例
  const addNewDeviceInstance = (device: Device) => {
    // 检查创建权限
    if (!canCreate) {
      toast({
        title: '权限不足',
        description: '您没有创建设备实例的权限',
        variant: 'destructive'
      });
      return;
    }

    console.log('添加新设备实例，原始设备信息:', device);
    const newDevice: DeviceInstance = {
      id: 0, // 临时ID，保存时会获得真实ID
      device_type_code: device.device_id,
      instance_number: '', // 自动生成
      object_number: '', // 对象编号，需要用户填写
      object_description: '', // 对象描述
      created_at: '',
      updated_at: '',
      isEditing: true,
      isNew: true,
      tempInstanceId: Date.now() + Math.random(), // 唯一的临时ID
      // 添加表信息以便在编辑时使用
      naming_table_display: device.naming_table_display,
      position_table_display: device.position_table_display,
      base_params_table_display: device.base_params_table_display
    };
    console.log('创建的新设备实例:', newDevice);

    setDeviceInstances(prev => ({
      ...prev,
      [device.device_id]: [...(prev[device.device_id] || []), newDevice]
    }));
  };

  // 保存设备实例
  const saveDeviceInstance = async (deviceId: string, deviceIndex: number, device: DeviceInstance) => {
    if (!device.object_number.trim()) {
      toast({
        title: '错误',
        description: '对象编号不能为空',
        variant: 'destructive'
      });
      return;
    }

    // 创建唯一的保存键来防止重复提交
    const saveKey = `${deviceId}_${deviceIndex}`;
    if (savingInstances.has(saveKey)) {
      console.log('设备实例正在保存中，忽略重复请求');
      return;
    }

    // 标记为保存中
    setSavingInstances(prev => new Set(prev).add(saveKey));

    try {
      if (device.isNew) {
        // 获取临时保存的参数数据
        const tempInstanceId = device.tempInstanceId || Date.now();
        const parameterData = getTempParameterData(tempInstanceId, device.device_type_code);
        console.log('🔍 [FRONTEND] === 设备保存时获取的临时参数数据 ===');
        console.log('🔍 [FRONTEND] tempInstanceId:', tempInstanceId);
        console.log('🔍 [FRONTEND] device.device_type_code:', device.device_type_code);
        console.log('🔍 [FRONTEND] parameterData:', JSON.stringify(parameterData, null, 2));

        // 创建新设备实例（包含参数数据和PBS信息）
        const requestBody = {
          device_type_code: device.device_type_code,
          object_number: device.object_number.trim(),
          object_description: device.object_description?.trim() || '',
          pbs_level_id: device.pbs_level_id || null,
          pbs_instance_id: device.pbs_instance_id || null,
          parameterData: parameterData  // 包含参数数据
        };
        
        console.log('🔍 [FRONTEND] === 发送到API的完整请求体 ===');
        console.log('🔍 [FRONTEND] requestBody:', JSON.stringify(requestBody, null, 2));
        
        const response = await fetch('/api/device-instances', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(requestBody)
        });

        const data = await response.json();
        
        if (data.success) {
          // 获取新设备实例的真实ID
          const newInstanceId = data.data.id;
          const tempInstanceId = device.tempInstanceId || Date.now(); // 使用设备的临时ID
          
          console.log('设备实例保存成功，参数数据已关联:', {
            tempInstanceId,
            newInstanceId,
            device_type_code: device.device_type_code,
            embeddedParameterFields: Object.keys(data.data).filter(key => 
              key.startsWith('naming_') || key.startsWith('position_') || key.startsWith('base_params_')
            )
          });
          
          // 清理临时参数数据（因为已经保存到数据库）
          try {
            // Clean both possible key formats
            localStorage.removeItem(`tempParams_${tempInstanceId}_${device.device_type_code}`);
            localStorage.removeItem(`tempParams_${tempInstanceId}`);
            console.log('清理临时参数数据成功');
          } catch (error) {
            console.error('清理临时数据失败:', error);
          }
          
          // 更新本地状态，保持表信息
          const currentDevice = deviceHierarchies
            .flatMap(h => h.devices)
            .find(d => d.device_id === device.device_type_code);
            
          const updatedDevice = {
            ...data.data,
            isNew: false,
            isEditing: false,
            naming_table_display: currentDevice?.naming_table_display,
            position_table_display: currentDevice?.position_table_display,
            base_params_table_display: currentDevice?.base_params_table_display
          };
          
          setDeviceInstances(prev => ({
            ...prev,
            [deviceId]: (prev[deviceId] || []).map((d, i) => i === deviceIndex ? updatedDevice : d)
          }));
          
          const embeddedParameterFields = Object.keys(data.data).filter(key => 
            key.startsWith('naming_') || key.startsWith('position_') || key.startsWith('base_params_')
          );
          const hasParameters = embeddedParameterFields.length > 0;
          toast({
            title: '成功',
            description: hasParameters ? '设备实例和参数数据已保存' : '设备实例已保存'
          });
        } else {
          throw new Error(data.error);
        }
      } else {
        // 更新现有设备实例
        const updatedDevice = {
          ...device,
          isEditing: false
        };
        
        setDeviceInstances(prev => ({
          ...prev,
          [deviceId]: (prev[deviceId] || []).map((d, i) => i === deviceIndex ? updatedDevice : d)
        }));
        
        toast({
          title: '成功',
          description: '设备信息已更新'
        });
      }
    } catch (error) {
      console.error('保存设备实例失败:', error);
      
      // 增强错误处理
      let errorMessage = '保存设备实例失败';
      if (error instanceof Error) {
        if (error.message.includes('实例编号冲突')) {
          errorMessage = '实例编号冲突，请重试';
        } else if (error.message.includes('实例编号已存在')) {
          errorMessage = '系统正在处理中，请稍后重试';
        } else {
          errorMessage = error.message;
        }
      }
      
      toast({
        title: '错误',
        description: errorMessage,
        variant: 'destructive'
      });
    } finally {
      // 清理保存状态
      setSavingInstances(prev => {
        const newSet = new Set(prev);
        newSet.delete(saveKey);
        return newSet;
      });
    }
  };

  // 取消编辑
  const cancelEdit = (deviceId: string, deviceIndex: number, device: DeviceInstance) => {
    if (device.isNew) {
      // 如果是新设备，直接删除
      setDeviceInstances(prev => ({
        ...prev,
        [deviceId]: (prev[deviceId] || []).filter((_, i) => i !== deviceIndex)
      }));
    } else {
      // 如果是编辑现有设备，恢复编辑状态
      setDeviceInstances(prev => ({
        ...prev,
        [deviceId]: (prev[deviceId] || []).map((d, i) => 
          i === deviceIndex ? { ...d, isEditing: false } : d
        )
      }));
    }
  };

  // 开始编辑设备
  const startEdit = (deviceId: string, deviceIndex: number) => {
    setDeviceInstances(prev => ({
      ...prev,
      [deviceId]: (prev[deviceId] || []).map((d, i) => 
        i === deviceIndex ? { ...d, isEditing: true } : d
      )
    }));
  };

  // 删除设备实例
  const deleteDeviceInstance = async (deviceId: string, deviceIndex: number, device: DeviceInstance) => {
    // 检查删除权限
    if (!canDelete) {
      toast({
        title: '权限不足',
        description: '您没有删除设备实例的权限',
        variant: 'destructive'
      });
      return;
    }

    if (!confirm(`确定要删除设备实例 "${device.object_number}" 吗？此操作不可撤销。`)) {
      return;
    }

    try {
      if (device.id > 0 && !device.isNew) {
        // 删除已保存的设备实例（需要调用API）
        const response = await fetch(`/api/device-instances?id=${device.id}`, {
          method: 'DELETE'
        });

        if (!response.ok) {
          throw new Error('删除设备实例失败');
        }
      }

      // 从本地状态中移除
      setDeviceInstances(prev => ({
        ...prev,
        [deviceId]: (prev[deviceId] || []).filter((_, i) => i !== deviceIndex)
      }));

      toast({
        title: '成功',
        description: '设备实例已删除'
      });
    } catch (error) {
      console.error('删除设备实例失败:', error);
      toast({
        title: '错误',
        description: error instanceof Error ? error.message : '删除设备实例失败',
        variant: 'destructive'
      });
    }
  };

  // 更新设备字段
  const updateDeviceField = (deviceId: string, deviceIndex: number, field: string, value: string) => {
    console.log('更新设备字段:', { deviceId, deviceIndex, field, value });
    setDeviceInstances(prev => {
      console.log('当前设备实例状态:', prev[deviceId]);
      const updated = {
        ...prev,
        [deviceId]: (prev[deviceId] || []).map((d, i) => 
          i === deviceIndex ? { ...d, [field]: value } : d
        )
      };
      console.log('更新后的设备实例:', updated[deviceId]);
      return updated;
    });
  };

  // 打开参数表弹窗
  const openParameterDialog = (instanceId: number, deviceName: string, tableName: string, tableType: string, classificationCode: string) => {
    console.log('=== openParameterDialog 被调用 ===');
    console.log('传入参数:', {
      instanceId,
      deviceName,
      tableName,
      tableType,
      classificationCode
    });
    
    setCurrentParameterTable({
      instanceId,
      deviceName,
      tableName,
      tableType,
      classificationCode
    });
    setParameterDialogOpen(true);
  };

  // 关闭参数表弹窗
  const closeParameterDialog = () => {
    setParameterDialogOpen(false);
    setCurrentParameterTable(null);
  };

  useEffect(() => {
    loadDeviceHierarchies();
  }, [specialty, subSpecialty]);

  if (loading) {
    return (
      <div className="flex items-center justify-center p-8">
        <Loader2 className="w-6 h-6 animate-spin mr-2" />
        <span>加载设备类型中...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center p-8">
        <AlertCircle className="w-6 h-6 text-red-500 mr-2" />
        <span className="text-red-600">{error}</span>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold">{specialty} - 设备类型管理</h2>
          <p className="text-gray-600 text-sm mt-1">
            展开设备类型查看子类型，在子类型下添加设备实例并录入对象编号和描述
          </p>
        </div>
        <Badge variant="outline">
          {deviceHierarchies.reduce((total, hierarchy) => total + hierarchy.devices.length, 0)} 个设备类型
        </Badge>
      </div>

      <div className="space-y-2">
        {deviceHierarchies.map((hierarchy) => {
          const isCategoryExpanded = expandedCategories.has(hierarchy.classification_name);

          return (
            <Card key={hierarchy.classification_name} className="overflow-hidden">
              {/* 设备分类级别 */}
              <Collapsible 
                open={isCategoryExpanded} 
                onOpenChange={() => toggleCategoryExpanded(hierarchy.classification_name)}
              >
                <CardHeader className="pb-3">
                  <CollapsibleTrigger asChild>
                    <Button variant="ghost" className="w-full justify-start p-0 h-auto">
                      <div className="flex items-center gap-2">
                        {isCategoryExpanded ? (
                          <ChevronDown className="w-4 h-4" />
                        ) : (
                          <ChevronRight className="w-4 h-4" />
                        )}
                        <div className="text-left flex-1">
                          <div className="font-bold text-lg text-blue-700">
                            {hierarchy.classification_name}
                          </div>
                          <div className="text-sm text-gray-500">
                            {hierarchy.devices.length} 个设备类型
                          </div>
                        </div>
                      </div>
                    </Button>
                  </CollapsibleTrigger>
                </CardHeader>

                <CollapsibleContent>
                  <CardContent className="pt-0">
                    {/* 设备类型列表 */}
                    <div className="space-y-2 ml-4">
                      {hierarchy.devices.map((deviceType) => {
                        const isDeviceExpanded = expandedDevices.has(deviceType.device_id);
                        const instances = deviceInstances[deviceType.device_id] || [];

                        return (
                          <Card key={deviceType.device_id} className="border-l-4 border-l-green-500">
                            {/* 设备类型信息和添加按钮 */}
                            <CardHeader className="pb-2">
                              <div className="flex items-center justify-between">
                                <div className="flex-1">
                                  <div className="font-medium text-sm">
                                    {deviceType.name}
                                  </div>
                                  <div className="text-xs text-gray-500">
                                    设备ID: {deviceType.device_id} | 分类码: {deviceType.classification_code}
                                    {deviceType.naming_table_display && (
                                      <span> | 表映射: {deviceType.naming_table_display} | {deviceType.position_table_display} | {deviceType.base_params_table_display}</span>
                                    )}
                                  </div>
                                </div>
                                
                                <div className="flex items-center gap-2">
                                  <PermissionGuard requireCreate>
                                    <Button
                                      size="sm"
                                      onClick={() => addNewDeviceInstance(deviceType)}
                                      className="flex items-center gap-1 h-7 text-xs"
                                    >
                                      <Plus className="w-3 h-3" />
                                      添加实例
                                    </Button>
                                  </PermissionGuard>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => toggleDeviceExpanded(deviceType.device_id)}
                                    className="flex items-center gap-1 h-7 text-xs"
                                  >
                                    {isDeviceExpanded ? (
                                      <ChevronDown className="w-3 h-3" />
                                    ) : (
                                      <ChevronRight className="w-3 h-3" />
                                    )}
                                    {instances.length} 个实例
                                  </Button>
                                </div>
                              </div>
                            </CardHeader>

                            {/* 设备实例列表（可折叠） */}
                            <Collapsible 
                              open={isDeviceExpanded}
                              onOpenChange={() => toggleDeviceExpanded(device.device_id)}
                            >
                              <CollapsibleContent>
                                <CardContent className="pt-0">
                                  {instances.length === 0 ? (
                                    <div className="text-center py-4 text-gray-500 text-sm">
                                      暂无设备实例，点击"添加实例"按钮创建
                                    </div>
                                  ) : (
                                    <div className="space-y-2">
                                      {instances.map((device, deviceIndex) => (
                                        <div 
                                          key={device.id || `temp-${deviceIndex}`} 
                                          className={`p-3 rounded-md border transition-colors ${
                                            device.isNew ? 'bg-yellow-50 border-yellow-200' : 'bg-gray-50 border-gray-200'
                                          }`}
                                        >
                                          {device.isEditing ? (
                                            /* 编辑模式 */
                                            <div className="space-y-4">
                                              
                                              <div className="space-y-3">
                                                <div className="grid grid-cols-2 gap-2">
                                                  <div>
                                                    <Label className="text-xs text-gray-600">对象编号 *</Label>
                                                    <Input
                                                      placeholder="如: P-001-001"
                                                      value={device.object_number || ''}
                                                      onChange={(e) => {
                                                        console.log('输入框onChange触发:', e.target.value);
                                                        updateDeviceField(deviceType.device_id, deviceIndex, 'object_number', e.target.value);
                                                      }}
                                                      onFocus={() => console.log('输入框获得焦点')}
                                                      onBlur={() => console.log('输入框失去焦点')}
                                                      className="h-8 text-sm"
                                                      autoComplete="off"
                                                    />
                                                  </div>
                                                  <div>
                                                    <Label className="text-xs text-gray-600">对象描述</Label>
                                                    <Input
                                                      placeholder="如: 离心泵#1"
                                                      value={device.object_description || ''}
                                                      onChange={(e) => updateDeviceField(deviceType.device_id, deviceIndex, 'object_description', e.target.value)}
                                                      className="h-8 text-sm"
                                                    />
                                                  </div>
                                                </div>
                                                
                                                {/* PBS层级选择器 */}
                                                <div>
                                                  <Label className="text-xs text-gray-600 mb-2 block">PBS层级选择</Label>
                                                  <PBSLevelSelector
                                                    instanceId={device.id > 0 ? device.id.toString() : device.object_number || ''}
                                                    value={device.pbs_level_id || 0}
                                                    onSelect={(pbsLevelId: number, pbsInstanceId: string) => {
                                                      updateDeviceField(deviceType.device_id, deviceIndex, 'pbs_level_id', pbsLevelId);
                                                      updateDeviceField(deviceType.device_id, deviceIndex, 'pbs_instance_id', pbsInstanceId);
                                                    }}
                                                    placeholder="选择PBS层级..."
                                                  />
                                                  {device.pbs_instance_id && (
                                                    <div className="mt-1 text-xs text-gray-500">
                                                      PBS实例ID: {device.pbs_instance_id}
                                                    </div>
                                                  )}
                                                </div>
                                              </div>
                                              
                                              {/* 参数表录入区域 */}
                                              {device.naming_table_display && (
                                                <div>
                                                  <Label className="text-xs text-gray-600 mb-2 block">参数表录入</Label>
                                                  <div className="grid grid-cols-3 gap-2">
                                                    <Button
                                                      variant="outline"
                                                      size="sm"
                                                      className="h-10 text-xs flex items-center gap-1"
                                                      onClick={() => {
                                                        console.log('=== C.2 参数表按钮点击 ===');
                                                        console.log('设备状态:', {
                                                          id: device.id,
                                                          isNew: device.isNew,
                                                          object_number: device.object_number,
                                                          device_type_code: device.device_type_code
                                                        });
                                                        
                                                        // 找到对应的device信息
                                                        const currentDevice = hierarchy.devices.find(d => d.device_id === device.device_type_code);
                                                        console.log('找到的设备类型:', currentDevice);
                                                        console.log('命名表信息:', {
                                                          naming_table: currentDevice?.naming_table,
                                                          position_table: currentDevice?.position_table,
                                                          base_params_table: currentDevice?.base_params_table
                                                        });
                                                        console.log('完整设备信息:', JSON.stringify(currentDevice, null, 2));
                                                        
                                                        // 暂时跳过保存检查，允许新设备也能录入参数
                                                        if (device.object_number && device.object_number.trim()) {
                                                          console.log('打开参数对话框...');
                                                          // 对于新设备，使用临时ID
                                                          const instanceId = device.id > 0 ? device.id : (device.tempInstanceId || Date.now());
                                                          console.log('编辑模式 C.2 按钮 - 详细信息:', {
                                                            naming_table: currentDevice?.naming_table,
                                                            naming_table_display: currentDevice?.naming_table_display,
                                                            传递的表名: currentDevice?.naming_table || '空值'
                                                          });
                                                          
                                                          // 确保传递正确的数据库表名，而不是显示名称
                                                          const actualTableName = currentDevice?.naming_table || 'table_c2';
                                                          console.log('实际传递的表名:', actualTableName);
                                                          
                                                          openParameterDialog(
                                                            instanceId,
                                                            device.object_number || '设备实例',
                                                            actualTableName,
                                                            'naming',
                                                            currentDevice?.classification_code || ''
                                                          );
                                                        } else {
                                                          alert('请先填写对象编号');
                                                          console.log('对象编号为空，不能录入参数');
                                                        }
                                                      }}
                                                    >
                                                      <Database className="w-3 h-3" />
                                                      <span>{device.naming_table_display || '命名信息表'}</span>
                                                    </Button>
                                                    <Button
                                                      variant="outline"
                                                      size="sm"
                                                      className="h-10 text-xs flex items-center gap-1"
                                                      onClick={() => {
                                                        console.log('=== C.6 参数表按钮点击 ===');
                                                        const currentDevice = hierarchy.devices.find(d => d.device_id === device.device_type_code);
                                                        
                                                        if (device.object_number && device.object_number.trim()) {
                                                          console.log('打开位置参数对话框...');
                                                          console.log('位置表信息:', {
                                                            position_table: currentDevice?.position_table,
                                                            position_table_display: currentDevice?.position_table_display
                                                          });
                                                          const instanceId = device.id > 0 ? device.id : (device.tempInstanceId || Date.now());
                                                          const actualTableName = currentDevice?.position_table || 'table_c6';
                                                          console.log('C.6按钮实际传递的表名:', actualTableName);
                                                          openParameterDialog(
                                                            instanceId,
                                                            device.object_number || '设备实例',
                                                            actualTableName,
                                                            'position',
                                                            currentDevice?.classification_code || ''
                                                          );
                                                        } else {
                                                          alert('请先填写对象编号');
                                                        }
                                                      }}
                                                    >
                                                      <Database className="w-3 h-3" />
                                                      <span>{device.position_table_display || '位置信息表'}</span>
                                                    </Button>
                                                    <Button
                                                      variant="outline"
                                                      size="sm"
                                                      className="h-10 text-xs flex items-center gap-1"
                                                      onClick={() => {
                                                        console.log('=== C.494 参数表按钮点击 ===');
                                                        const currentDevice = hierarchy.devices.find(d => d.device_id === device.device_type_code);
                                                        
                                                        if (device.object_number && device.object_number.trim()) {
                                                          console.log('打开基础参数对话框...');
                                                          const instanceId = device.id > 0 ? device.id : (device.tempInstanceId || Date.now());
                                                          const actualTableName = currentDevice?.base_params_table || 'table_c494';
                                                          console.log('C.494按钮实际传递的表名:', actualTableName);
                                                          openParameterDialog(
                                                            instanceId,
                                                            device.object_number || '设备实例',
                                                            actualTableName,
                                                            'base',
                                                            currentDevice?.classification_code || ''
                                                          );
                                                        } else {
                                                          alert('请先填写对象编号');
                                                        }
                                                      }}
                                                    >
                                                      <Database className="w-3 h-3" />
                                                      <span>{device.base_params_table_display || '基础参数表'}</span>
                                                    </Button>
                                                  </div>
                                                </div>
                                              )}
                                              
                                              <div className="flex items-center gap-2 justify-end">
                                                <Button
                                                  size="sm"
                                                  variant="outline"
                                                  onClick={() => cancelEdit(deviceType.device_id, deviceIndex, device)}
                                                  className="h-7 text-xs"
                                                >
                                                  取消
                                                </Button>
                                                <Button
                                                  size="sm"
                                                  onClick={() => saveDeviceInstance(deviceType.device_id, deviceIndex, device)}
                                                  className="h-7 text-xs"
                                                  disabled={!device.object_number.trim() || savingInstances.has(`${deviceType.device_id}_${deviceIndex}`)}
                                                >
                                                  {savingInstances.has(`${deviceType.device_id}_${deviceIndex}`) ? (
                                                    <>
                                                      <Loader2 className="w-3 h-3 mr-1 animate-spin" />
                                                      保存中...
                                                    </>
                                                  ) : (
                                                    '保存'
                                                  )}
                                                </Button>
                                              </div>
                                            </div>
                                          ) : (
                                            /* 显示模式 */
                                            <div className="space-y-2">
                                              <div className="flex items-center justify-between">
                                                <div className="flex-1">
                                                  <div className="font-medium text-sm">
                                                    实例#{device.instance_number}: {device.object_number}
                                                  </div>
                                                  {device.object_description && (
                                                    <div className="text-xs text-gray-600">{device.object_description}</div>
                                                  )}
                                                  {device.pbs_instance_id && (
                                                    <div className="text-xs text-blue-600 mt-1">
                                                      PBS层级ID: {device.pbs_instance_id}
                                                    </div>
                                                  )}
                                                </div>
                                                <div className="flex items-center gap-1">
                                                  <PermissionGuard requireCreate>
                                                    <Button
                                                      variant="ghost"
                                                      size="sm"
                                                      className="h-7 text-xs"
                                                      onClick={() => startEdit(deviceType.device_id, deviceIndex)}
                                                    >
                                                      编辑
                                                    </Button>
                                                  </PermissionGuard>
                                                  <PermissionGuard requireDelete>
                                                    <Button
                                                      variant="ghost"
                                                      size="sm"
                                                      className="h-7 text-xs text-red-600 hover:text-red-700 hover:bg-red-50"
                                                      onClick={() => deleteDeviceInstance(deviceType.device_id, deviceIndex, device)}
                                                    >
                                                      删除
                                                    </Button>
                                                  </PermissionGuard>
                                                </div>
                                              </div>
                                              
                                              {/* 参数表访问行 - 只对已保存的实例显示 */}
                                              {device.id > 0 && !device.isNew && (
                                                <div className="pt-2 border-t border-gray-200">
                                                  <div className="grid grid-cols-3 gap-1">
                                                    <Button
                                                      variant="outline"
                                                      size="sm"
                                                      className="h-8 text-xs bg-blue-50 border-blue-300 hover:bg-blue-100"
                                                      onClick={() => {
                                                        const currentDevice = hierarchy.devices.find(d => d.device_id === device.device_type_code);
                                                        if (currentDevice) {
                                                          console.log('显示模式 C.2 按钮 - 设备信息:', currentDevice);
                                                          console.log('实际表名:', currentDevice.naming_table);
                                                          console.log('显示名称:', currentDevice.naming_table_display);
                                                          const actualTableName = currentDevice.naming_table || 'table_c2';
                                                          openParameterDialog(
                                                            device.id,
                                                            device.object_number,
                                                            actualTableName,
                                                            'naming',
                                                            currentDevice.classification_code || ''
                                                          );
                                                        }
                                                      }}
                                                    >
                                                      <Database className="w-3 h-3 mr-1" />
                                                      {device.naming_table_display || '命名信息表'}
                                                    </Button>
                                                    <Button
                                                      variant="outline"
                                                      size="sm"
                                                      className="h-8 text-xs bg-green-50 border-green-300 hover:bg-green-100"
                                                      onClick={() => {
                                                        const currentDevice = hierarchy.devices.find(d => d.device_id === device.device_type_code);
                                                        if (currentDevice) {
                                                          const actualTableName = currentDevice.position_table || 'table_c6';
                                                          openParameterDialog(
                                                            device.id,
                                                            device.object_number,
                                                            actualTableName,
                                                            'position',
                                                            currentDevice.classification_code || ''
                                                          );
                                                        }
                                                      }}
                                                    >
                                                      <Database className="w-3 h-3 mr-1" />
                                                      {device.position_table_display || '位置信息表'}
                                                    </Button>
                                                    <Button
                                                      variant="outline"
                                                      size="sm"
                                                      className="h-8 text-xs bg-orange-50 border-orange-300 hover:bg-orange-100"
                                                      onClick={() => {
                                                        const currentDevice = hierarchy.devices.find(d => d.device_id === device.device_type_code);
                                                        if (currentDevice) {
                                                          const actualTableName = currentDevice.base_params_table || 'table_c494';
                                                          openParameterDialog(
                                                            device.id,
                                                            device.object_number,
                                                            actualTableName,
                                                            'base',
                                                            currentDevice.classification_code || ''
                                                          );
                                                        }
                                                      }}
                                                    >
                                                      <Database className="w-3 h-3 mr-1" />
                                                      {device.base_params_table_display || '基础参数表'}
                                                    </Button>
                                                </div>
                                                </div>
                                              )}
                                            </div>
                                          )}
                                        </div>
                                      ))}
                                    </div>
                                  )}
                                </CardContent>
                              </CollapsibleContent>
                            </Collapsible>
                          </Card>
                        );
                      })}
                    </div>
                  </CardContent>
                </CollapsibleContent>
              </Collapsible>
            </Card>
          );
        })}
      </div>
      
      {/* 参数表录入弹窗 */}
      <Dialog open={parameterDialogOpen} onOpenChange={setParameterDialogOpen}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {currentParameterTable && (
                <div className="flex items-center gap-2">
                  <Database className="w-5 h-5" />
                  <span>
                    {currentParameterTable.deviceName} - 
                    {currentParameterTable.tableType === 'naming' && '命名信息表'}
                    {currentParameterTable.tableType === 'position' && '位置信息表'}
                    {currentParameterTable.tableType === 'base' && '基础参数表'}
                  </span>
                  <Badge variant="outline">{currentParameterTable.tableName}</Badge>
                </div>
              )}
            </DialogTitle>
            <DialogDescription>
              录入设备的参数信息，完成后点击保存。
            </DialogDescription>
          </DialogHeader>
          
          <div className="py-4">
            {currentParameterTable && (
              <ParameterEntryDialog
                tableName={currentParameterTable.tableName}
                instanceId={currentParameterTable.instanceId}
                deviceName={currentParameterTable.deviceName}
                tableType={currentParameterTable.tableType}
                classificationCode={currentParameterTable.classificationCode}
                onSave={() => {
                  toast({
                    title: '保存成功',
                    description: '参数数据已保存'
                  });
                  closeParameterDialog();
                }}
              />
            )}
          </div>
          
          <DialogFooter>
            <Button variant="outline" onClick={closeParameterDialog}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}